/**
 * 京东联盟实时热销榜查询模块
 * @version 1.0.0
 * @author 开发者
 * @see {@link https://union.jd.com/openplatform/api/1227|京东联盟API文档}
 */

const {
  normalizePayload,
  normalizeDbConfig,
  buildSignParams,
  buildJdSign,
  parseJdQueryResult,
  persistDocs,
  JD_API_URL,
  mapRankGoodsDoc,
  buildQueryResultMeta
} = require('./@utils')

/**
 * 调用京东联盟实时热销榜接口
 *
 * @param {object} payload 请求参数
 * @param {object} [payload.auth] 认证信息
 * @param {string} [payload.auth.appKey] 京东联盟appKey（可使用全局配置）
 * @param {string} [payload.auth.appSecret] 京东联盟appSecret（可使用全局配置）
 * @param {string} [payload.auth.accessToken] 访问令牌
 * @param {object} payload.query 查询参数
 * @param {number} payload.query.rankId 榜单ID
 * @param {number} payload.query.sortType 排序类型
 * @param {number} [payload.query.pageIndex=1] 页码
 * @param {number} [payload.query.pageSize=20] 每页数量（最大20）
 * @param {object} [payload.options] 可选配置
 * @param {string|object} [payload.options.db] 数据库配置（字符串为集合名，对象为详细配置）
 * @returns {Promise<{requestParams: object, response: any, queryResult?: object, dbResult?: any}>}
 * @example
 * // 新格式（推荐）
 * await queryRankGoods({
 *   query: { rankId: 1, sortType: 1, pageIndex: 1, pageSize: 20 },
 *   options: { db: 'jd_rank_goods' }
 * })
 *
 * @example
 * // 旧格式（兼容）
 * await queryRankGoods({
 *   appKey: 'xxx',
 *   appSecret: 'xxx',
 *   rankId: 1,
 *   sortType: 1,
 *   persistence: { enable: true, collection: 'jd_rank_goods' }
 * })
 */
async function queryRankGoods(payload) {
  // 标准化参数
  const { auth, query, options } = normalizePayload(payload)

  const {
    rankId,
    sortType,
    pageIndex = 1,
    pageSize = 20, // 默认20，也是最大值
    rankGoodsReq,
    bizParamKey = 'RankGoodsReq',
    custom360buyParamJson
  } = query

  let businessParams
  if (custom360buyParamJson) {
    if (typeof custom360buyParamJson !== 'string') {
      throw new Error('custom360buyParamJson必须是字符串')
    }
    businessParams = custom360buyParamJson
  } else {
    if (typeof rankId !== 'number') {
      throw new Error('rankId必须为数字')
    }
    if (typeof sortType !== 'number') {
      throw new Error('sortType必须为数字')
    }
    const safePageSize = Math.max(1, Math.min(pageSize, 20))
    const payloadBody = rankGoodsReq || {
      rankId,
      sortType,
      pageIndex,
      pageSize: safePageSize
    }
    businessParams = {
      [bizParamKey]: payloadBody
    }
  }

  const { params, appSecret: secret } = buildSignParams({
    appKey: auth.appKey,
    appSecret: auth.appSecret,
    method: 'jd.union.open.goods.rank.query',
    businessParams,
    timestamp: options.timestamp,
    version: options.version,
    format: options.format,
    signMethod: options.signMethod,
    accessToken: auth.accessToken
  })
  const { sign } = buildJdSign(secret, params)
  const requestParams = {
    ...params,
    sign
  }

  const { status, data } = await uniCloud.httpclient.request(JD_API_URL, {
    method: 'POST',
    data: requestParams,
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded',
    timeout: 10000
  })

  if (status !== 200) {
    throw new Error(`京东联盟接口请求失败，HTTP状态码：${status}`)
  }

  const queryResult = parseJdQueryResult(data)

  // 处理数据库持久化
  let dbResult
  const dbConfig = normalizeDbConfig(options.db)
  if (dbConfig) {
    dbResult = await persistDocs({
      collectionName: dbConfig.collection,
      list: Array.isArray(queryResult?.data) ? queryResult.data : [],
      transform: mapRankGoodsDoc,
      uniqueKeys: dbConfig.uniqueKeys,
      extraDocFields: {
        requestParams,
        queryResultMeta: buildQueryResultMeta(queryResult),
        ...(dbConfig.extraFields || {})
      }
    })
  }

  // 根据 debug 选项决定返回格式
  if (options.debug) {
    return {
      requestParams,
      response: data,
      queryResult,
      dbResult
    }
  }

  // 默认只返回 queryResult
  return queryResult
}

module.exports = queryRankGoods
